<template>
  <view class="select-wrapper" @click="open" :class="{ disabled: disabled }">
    <slot>
      <view class="selector">
        <view class="selector-content">
          <text class="selector-text" :class="{ placeholder: !displayLabel }">{{ displayLabel || placeholder }}</text>
          <uni-icons type="down" size="14" color="#999"></uni-icons>
        </view>
      </view>
    </slot>
  </view>

  <uni-popup ref="popupRef" type="bottom" :mask-click="true">
    <view class="bottom-sheet">
      <view class="bottom-sheet-header">
        <text class="bottom-sheet-title">{{ title }}</text>
        <uni-icons type="close" size="20" @click="close"></uni-icons>
      </view>
      <view class="bottom-sheet-body">
        <da-tree
          ref="treeRef"
          :data="treeData"
          :show-checkbox="false"
          :show-radio-icon="true"
          :default-checked-keys="modelValue ? [modelValue] : []"
          :field="{
            value: valueField,
            label: labelField,
            children: childrenField
          }"
          :indent="20"
          @change="onTreeChange">
        </da-tree>
      </view>
      <view class="bottom-sheet-footer">
        <view class="btn btn-cancel" @click="close">取消</view>
        <view class="btn btn-confirm" @click="confirm">确定</view>
      </view>
    </view>
  </uni-popup>
</template>

<script setup>
import { ref, computed } from 'vue'
import DaTree from '@/components/da-tree/index.vue'

const props = defineProps({
  modelValue: [String, Number],
  treeData: { type: Array, default: () => [] },
  valueField: { type: String, default: 'deptId' },
  labelField: { type: String, default: 'deptName' },
  childrenField: { type: String, default: 'children' },
  placeholder: { type: String, default: '请选择' },
  title: { type: String, default: '请选择' },
  disabled: { type: Boolean, default: false }
})

const emit = defineEmits(['update:modelValue', 'change'])
const popupRef = ref(null)
const tempValue = ref(null)

const displayLabel = computed(() => {
  if (props.modelValue === undefined || props.modelValue === null || !props.treeData || props.treeData.length === 0) {
    return ''
  }
  
  const find = (nodes, val) => {
    for (const n of nodes) {
      // 确保类型匹配，转换为字符串进行比较
      const nodeValue = String(n[props.valueField])
      const targetValue = String(val)
      
      if (nodeValue === targetValue) {
        return n[props.labelField]
      }
      
      // 递归查找子节点
      if (n[props.childrenField] && Array.isArray(n[props.childrenField]) && n[props.childrenField].length > 0) {
        const result = find(n[props.childrenField], val)
        if (result) return result
      }
    }
    return ''
  }
  
  return find(props.treeData, props.modelValue)
})

function open() { 
  if (props.disabled) return
  tempValue.value = props.modelValue
  popupRef.value?.open() 
}

function close() { popupRef.value?.close() }

function onTreeChange(val) { 
  // 处理 da-tree 组件可能传递节点对象的情况
  if (val && typeof val === 'object' && val[props.valueField] !== undefined) {
    tempValue.value = val[props.valueField]
  } else {
    tempValue.value = val
  }
  
  // 单选模式下直接更新值并关闭弹窗
  emit('update:modelValue', tempValue.value)
  emit('change', tempValue.value)
  close()
}

function confirm() { 
  emit('update:modelValue', tempValue.value)
  emit('change', tempValue.value)
  close() 
}
</script>

<style scoped lang="scss">
.select-wrapper.disabled {
  opacity: 0.6;
  pointer-events: none;
}

.selector { border: 1px solid #ddd; border-radius: 6px; padding: 8px 12px; background-color: #fff; }
.selector-content { display: flex; align-items: center; justify-content: space-between; }
.selector-text { font-size: 14px; color: #333; }
.selector-text.placeholder { color: #999; }

.bottom-sheet { background: #fff; border-top-left-radius: 12px; border-top-right-radius: 12px; }
.bottom-sheet-header { display: flex; justify-content: space-between; align-items: center; padding: 12px 16px; border-bottom: 1px solid #eee; }
.bottom-sheet-title { font-size: 16px; font-weight: 600; color: #333; }
.bottom-sheet-body { 
  max-height: 60vh; 
  overflow-y: auto; 
  padding: 12px 16px 24px 16px; 
}
.bottom-sheet-footer { display: flex; justify-content: flex-end; gap: 8px; padding: 12px 16px; border-top: 1px solid #eee; }
.btn { padding: 6px 14px; font-size: 14px; border-radius: 6px; }
.btn-cancel { background-color: #f8f8f8; color: #666; border: 1px solid #d9d9d9; }
.btn-confirm { background-color: #e6f7ff; color: #007aff; border: 1px solid #91d5ff; }
</style>


